//
//  SingerMusicList.m
//  YanMusicPlayer
//
//  Created by 1564335 on 15-6-12.
//  Copyright (c) 2015年 胡岩 All rights reserved.
//

#import "SingerMusicList.h"
#import "SingerMusicListModel.h"
#import "SingerMusicListTableView.h"
#import "SingerMusicListTableViewCell.h"
@interface SingerMusicList ()<UITableViewDataSource, UITableViewDelegate, TouchTableDelegate>
{
    CGFloat x;
}
@property(nonatomic, strong) NSString *SingerName;

@property(nonatomic, strong) NSMutableArray *arrayData;

@property(nonatomic, strong) SingerMusicListTableView *singerMusicListTableView;

@property(nonatomic, assign) CGPoint startPoint;

@property(nonatomic, strong) NSMutableArray *urlArray;

@property(nonatomic, strong) UIActivityIndicatorView *activity;

@property(nonatomic, assign) BOOL isScroll;

@property(nonatomic, strong) UILabel *label;

@end

@implementation SingerMusicList

- (instancetype)initWithFrame:(CGRect)frame Singername:(NSString *)SingerName isScroll:(BOOL)isScroll
{
    _SingerName = [NSString string];
    _SingerName = SingerName;
    _arrayData = [NSMutableArray array];
    _urlArray = [NSMutableArray array];
    _isScroll = isScroll;
    self = [super initWithFrame:frame];
    if (self) {
        _activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        [self addSubview:_activity];
        [_activity startAnimating];
        _activity.center = self.center;
        [self netWorkMananger];
    }
    return self;
}

- (void)netWorkMananger
{
    NSString *path = nil;
    if (_isScroll) {
        path = _SingerName;
    } else {
        path = [[URLPath SingerMusicListURL] stringByAppendingFormat:@"page=1&q=%@&size=50", _SingerName];
        path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = dic[@"data"];
        for (NSDictionary *dic in array) {
            SingerMusicListModel *model = [[SingerMusicListModel alloc] initWithDic:dic];
            [self.arrayData addObject:model];
            MusicModel *musicModel = [MusicModel getMusicModel];
            musicModel.url = model.url;
            musicModel.singerName = model.singer_name;
            musicModel.songName = model.song_name;
            musicModel.lrcId = model.song_id;
            musicModel.singerId = model.singer_id;
            musicModel.songId = model.song_id;
            musicModel.musicLength = model.duration;
            [self.urlArray addObject:musicModel];
        }
        [self createView];
        [_activity stopAnimating];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [_activity stopAnimating];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败!" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }];

}

- (void)tableView:(UITableView *)tableView touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    self.startPoint = [touch locationInView:self];
}

- (void)tableView:(UITableView *)tableView touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (x > 0) {
        self.singerMusicListTableView.scrollEnabled = YES;
        self.singerMusicListTableView.userInteractionEnabled = YES;
        _singerMusicListTableView.allowsSelection = YES;
    }
    [self.touchTableViewDelegate sendTableViewTouchEnd];
}

- (void)tableView:(UITableView *)tableView touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint newPoint = [touch locationInView:self];
    x = newPoint.x - self.startPoint.x;
    if (x > 5 || x < -5) {
        self.singerMusicListTableView.scrollEnabled = NO;
        self.singerMusicListTableView.allowsSelection = NO;
        [self.touchTableViewDelegate getTableViewTouch:x];
    }
}

- (void)createView
{
    _label = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, self.frame.size.width - 200, 30)];
    _singerMusicListTableView = [[SingerMusicListTableView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) style:UITableViewStylePlain];
    _singerMusicListTableView.backgroundColor = [UIColor clearColor];
    _singerMusicListTableView.touchTableDelegate = self;
    [self addSubview:_singerMusicListTableView];
    _singerMusicListTableView.delegate = self;
    _singerMusicListTableView.dataSource = self;
    _singerMusicListTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    if (!_isScroll && _arrayData.count > 0) {
        [_singerMusicListTableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(refresh:)];
    }
    if (_arrayData.count == 0) {
        UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 30)];
        lable.text = @"暂无可听歌曲";
        [self addSubview:lable];
        lable.textAlignment = NSTextAlignmentCenter;
        lable.alpha = 0.7;
        lable.center = self.center;
    }
}

- (void)refresh:(SingerMusicListTableView *)tableView
{
    [_singerMusicListTableView.legendFooter beginRefreshing];
    static NSInteger number = 1;
    NSString *path = [[URLPath SingerMusicListURL] stringByAppendingFormat:@"page=%ld&q=%@&size=50", ++number,_SingerName];
    path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
        
        NSArray *array = dic[@"data"];
        for (NSDictionary *dic in array) {
            SingerMusicListModel *model = [[SingerMusicListModel alloc] initWithDic:dic];
            if (model.singer_name != nil && ![model.singer_name isEqual:[NSNull null]]) {
                [self.arrayData addObject:model];
                MusicModel *musicModel = [MusicModel getMusicModel];
                musicModel.url = model.url;
                musicModel.singerName = model.singer_name;
                musicModel.lrcId = model.song_id;
                musicModel.songName = model.song_name;
                musicModel.singerId = model.singer_id;
                musicModel.songId = model.song_id;
                musicModel.musicLength = model.duration;
                [_urlArray addObject:musicModel];
            }
        }

        [_singerMusicListTableView.legendFooter endRefreshing];
        [_singerMusicListTableView reloadData];
//         [[MusicPlayer1 shareInstance] loadMusicList:_urlArray];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [_singerMusicListTableView.legendFooter endRefreshing];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败!" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    SingerMusicListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[SingerMusicListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    SingerMusicListModel *model = [self.arrayData objectAtIndex:indexPath.row];
    cell.collectBtn.tag =  indexPath.row;
    cell.downloadBtn.tag = indexPath.row;
    [cell.collectBtn addTarget:self action:@selector(collect:) forControlEvents:UIControlEventTouchUpInside];
//    [cell.downloadBtn addTarget:self action:@selector(download:) forControlEvents:UIControlEventTouchUpInside];
    cell.contentView.backgroundColor = [UIColor colorWithRed:227/255.0 green:233/255.0 blue:240/255.0 alpha:1];
    if (indexPath.row % 2 == 0) {
        cell.contentView.backgroundColor = [UIColor colorWithRed:227/255.0 green:233/255.0 blue:240/255.0 alpha:1];
    } else {

        cell.contentView.backgroundColor = [UIColor whiteColor];
    }

    
    
    NSArray *array = [Database selectData:@""];
//    NSArray *downloadArray = [Database selectDownloadData];
    BOOL isOK = YES;
    BOOL isDownLoad = YES;
//    for (MusicModel *downloadModel in downloadArray) {
//        if ([downloadModel.songId integerValue] == [model.song_id integerValue]) {
//            cell.downloadImage = @"iconfont-xiazaiwancheng";
//            isDownLoad = NO;
//            break;
//        }
//    }
//    if (isDownLoad) {
//        cell.downloadImage = @"iconfont-xiazai2";
//    }
    
    for (MusicModel *dbModel in array) {
        if ([dbModel.songId integerValue] == [model.song_id integerValue]) {
            cell.collectImage = @"iconfont-xihuan";
            isOK = NO;
            break;
        }
    }
    if (isOK) {
        cell.collectImage = @"iconfont-xihuan3";
    }
    [cell setSingerMusicListModel:model];
    return cell;
}

#pragma -mark 收藏
- (void)collect:(UIButton *)button
{
    MusicModel *model = [_urlArray objectAtIndex:button.tag];
    NSArray *array = [Database selectData:@""];
    BOOL isOK = YES;
    for (MusicModel *dbModel in array) {
        if ([dbModel.songId integerValue] == [model.songId integerValue]) {
            isOK = NO;
            break;
        }
    }
    if (isOK) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
        SingerMusicListTableViewCell *cell = [_singerMusicListTableView cellForRowAtIndexPath:indexPath];

        cell.collectImage = @"iconfont-xihuan";
        [_singerMusicListTableView reloadData];
        [[MusicPlayer1 shareInstance].collectList addObject:model];
        [Database insertValue:model];
    } else {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
        SingerMusicListTableViewCell *cell = [_singerMusicListTableView cellForRowAtIndexPath:indexPath];
        
        cell.collectImage = @"iconfont-xihuan3";
        [_singerMusicListTableView reloadData];
        [Database deleteValue:model.songId];
        NSArray *array = [Database selectData:@""];
        [[MusicPlayer1 shareInstance].collectList removeAllObjects];
        [[MusicPlayer1 shareInstance].collectList addObjectsFromArray:array];
    }
    if ([HearderView shareInstance].currentList == 0) {
        [[MusicPlayer1 shareInstance].list removeAllObjects];
        [[MusicPlayer1 shareInstance].list addObjectsFromArray:[MusicPlayer1 shareInstance].collectList];
        [[HearderView shareInstance].listTableView reloadData];
    }
}

#pragma -mark 下载
- (void)download:(UIButton *)button
{
    SingerMusicListModel *model = [self.arrayData objectAtIndex:button.tag];
    NSArray *array = [Database selectDownloadData];
    BOOL isHave = NO;
    for (MusicModel *musicModel in array) {
        if ([model.song_id integerValue] == [musicModel.songId integerValue]) {
            isHave = YES;
        }
    }
    
    if (!isHave) {
        button.userInteractionEnabled = NO;
        _label.text = @"正在下载";
        _label.center = self.center;
        _label.textAlignment = NSTextAlignmentCenter;
        _label.backgroundColor = [UIColor grayColor];
        _label.textColor = [UIColor whiteColor];
        [self addSubview:_label];
        _label.alpha = 0.9;
//        _label.backgroundColor = [UIColor blackColor];
        [UIView animateWithDuration:1.5 animations:^{
//            button.frame = CGRectMake(_WIDTH - 50, 20, 10, 10);
            _label.alpha = 1.0;
        } completion:^(BOOL finished) {
//            [_label removeFromSuperview];
            _label.alpha = 0.0;
        }];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager GET:model.url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSString *number = [_USERDEFAULT objectForKey:@"number"];
            NSString *musicName = [NSString stringWithFormat:@"music%@.mp3", number];
            MusicModel *musicModel = [MusicModel getMusicModel];
            musicModel.url = musicName;
            musicModel.singerName = model.singer_name;
            musicModel.songName = model.song_name;
            musicModel.lrcId = model.song_id;
            musicModel.singerId = model.singer_id;
            musicModel.songId = model.song_id;
            musicModel.musicLength = model.duration;
            [Database insertDownloadValue:musicModel];
            [[MusicPlayer1 shareInstance].downloadList addObject:musicModel];
            
            if ([HearderView shareInstance].currentList == 1) {
                [[MusicPlayer1 shareInstance].list removeAllObjects];
                [[MusicPlayer1 shareInstance].list addObjectsFromArray:[MusicPlayer1 shareInstance].downloadList];
                [[HearderView shareInstance].listTableView reloadData];
            }
            
            NSString *musicPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:musicName];
            
            [[NSFileManager defaultManager] createFileAtPath:musicPath contents:operation.responseData attributes:nil];
            NSInteger num = [number integerValue];
            number = [NSString stringWithFormat:@"%ld", ++num];
            [_USERDEFAULT setObject:number forKey:@"number"];
            [UIView animateWithDuration:0.5 animations:^{
                [_singerMusicListTableView reloadData];
                button.frame = CGRectMake(self.frame.size.width - 40, 15, 50 - 30, 50 - 30);
            } completion:^(BOOL finished) {
                
            }];
            button.userInteractionEnabled = YES;
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [UIView animateWithDuration:0.5 animations:^{
                button.frame = CGRectMake(self.frame.size.width - 40, 15, 50 - 30, 50 - 30);
            } completion:^(BOOL finished) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"下载失败" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
            }];
            
        }];
        
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"已经下载" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayData.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [HearderView shareInstance].currentList = 100;
    [[MusicPlayer1 shareInstance] loadMusicList:_urlArray];
    SingerMusicListModel *model = [self.arrayData objectAtIndex:indexPath.row];
    [self.touchTableViewDelegate goBackTableView:model.url number:indexPath.row];
}

@end
